CONTENTS | INDEX | PREV | NEXT
fgets
NAME
fgets - get a line from a file pointer
SYNOPSIS
#include <stdio.h>
char *ptr = fgets(buf, maxlen, fp);
char *buf;
int maxlen;
FILE *fp;
FUNCTION
fgets() gets a line from the specified file pointer, returning
the first argument (buf) or NULL if an error or EOF occurs.
fgets() stores the line in buf, up to maxlen characters. This
maximum includes a terminating newline 'n' and nul '0'.
It is common to get confused between gets(), fgets(), puts(), and
fputs(). gets() strips off any newline 'n' and puts() adds one
while fgets() keeps the newline at the end of the line and fputs()
does NOT add one. gets() and puts() work on stdin and stdout
while fgets() and fputs() work on arbitrary file pointers.
If more than maxlen - 1 characters are in the line fgets will
terminate operation and put a nul as the last character (so the
buffer is still a valid string).
NOTE
refer to the file_pointer manual page for general information
EXAMPLE
#include <stdio.h>
main()
{
unsigned char buf[128];
short i;
printf("Enter a line - ");
fflush(stdout);
if (fgets(buf, sizeof(buf), stdin) == NULL)
exit(1);
printf("In Hex: ");
for (i = 0; buf[i]; ++i)
printf(" %02x", buf[i]);
puts("");
return(0);
}
INPUTS
char *buf; buffer
int maxlen; maximum buffer size
FILE *fp; file pointer
RESULTS
char *ptr; buf if all is well, or NULL if error or EOF
SEE ALSO
gets, puts, fputs, fread, getc, fgetc